package com.example.spring_forum.interceptor;

import com.example.spring_forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component //加入到spring中
public class LoginInterceptor implements HandlerInterceptor {
   //从配置文件里面读取内容并赋值给变量defaultURL
   @Value("${forum_project.login.url}")
    private String defaultURL;

    /**
     * 预处理，请求的前置处理
     *
     * @return true 继续请求流程 false终止请求流程
     * @throws Exception
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        HttpSession session=request.getSession(false);
        if(session !=null && session.getAttribute(AppConfig.SESSION_USER_KRY) != null){
            return true;
        }

        //对defaultURL做校验，确保url是从根目录目录开始
        if(!defaultURL.startsWith("/")){
            defaultURL="/"+defaultURL; //拼接'/'要记得拼接在前
        }
        response.sendRedirect(defaultURL);
        return false ;
    }
}
